package org.xiaoxiao.servlet;

import org.xiaoxiao.dao.BookVoteDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/vote")
public class VoteServlet extends HttpServlet {
    private BookVoteDao dao = new BookVoteDao();

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 获取客户端IP
        String ip = request.getRemoteAddr();
        String bookId = request.getParameter("bookId");

        // 检查是否已投票
        if (dao.hasVoted(ip)) {
            request.setAttribute("error", "您已经投过票了，不能重复投票");
            request.getRequestDispatcher("/index.jsp").forward(request, response);
            return;
        }

        // 处理投票
        dao.addVote(bookId, ip);
        request.setAttribute("success", "投票成功");
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    }
}
